package com.hx.base.others;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author HP
 * <p>
 * <p>
 * <p>
 * 问题：给一个整数N和一个纯文本文件，从这个文件随机抽N行文本返回
 * <p>
 * 要求：文件只读一遍，占用的内存最多只有N+1行；返回的文本行顺序要跟原文件中的文本行顺序保持一致
 */
public class BootStrap {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        List<String> list = extractLines("D:/a.txt", 4);
        for (String string : list) {
            System.out.println(string);
        }
    }

    public static List<String> extractLines(String filePath, int n) {
        List<String> list = new ArrayList<>();
        String line = null;
        BufferedReader reader = null;
        int count = 0;
        Random random = new Random();
        int nextInt = random.nextInt(28 - n);
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
            while ((line = reader.readLine()) != null) {
                count++;
                if (count > nextInt) {
                    list.add(line);
                    if (list.size() >= n) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }


}
